import logging
import time
from common.yaml_util import get_object_path, read_config_yaml

class LoggerUtil:

    def create_log(self,logger_name='log111111'):
        # 创建一个日志对象
        self.logger=logging.getLogger(logger_name)

        # 设置全局日志级别（critical，errror，waning，info，debug）
        self.logger.setLevel(logging.DEBUG)

        # 防止日志重复
        if not self.logger.handlers:

            #===============文件日志====================
            # 1、获取日志文件的名称,写入文件，路径+文件名
            # self.file_log_path=get_object_path()+'/logs/'+read_config_yaml('log','log_name')+str(int(time.time()))
            self.file_log_path = get_object_path() + '/logs/' + 'logs_' + str(time.strftime("%Y-%m-%d", time.localtime()))

            # 2、创建文件日子控制器
            self.file_handler=logging.FileHandler(self.file_log_path,encoding='utf-8-sig')

            # 3、设置文件日志的级别
            file_log_lever=str(read_config_yaml('log','log_level')).lower()
            if file_log_lever == 'debug':
                self.file_handler.setLevel(logging.DEBUG)
            elif file_log_lever == 'info':
                self.file_handler.setLevel(logging.INFO)
            elif file_log_lever == 'warning':
                self.file_handler.setLevel(logging.WARNING)
            elif file_log_lever == 'error':
                self.file_handler.setLevel(logging.ERROR)
            elif file_log_lever == 'critical':
                self.file_handler.setLevel(logging.CRITICAL)

            # 4、设置文件日志格式
            self.file_handler.setFormatter(logging.Formatter(read_config_yaml('log','log_format')))

            # 5、将控制器加入日志对象 写入
            self.logger.addHandler(self.file_handler)





            # ===============控制台如日志====================
            # 创建控制台日志控制器
            self.console_handler=logging.StreamHandler()

            # 设置控制台日志的级别
            console_log_lever=str(read_config_yaml('log','log_level')).lower()
            if console_log_lever == 'debug':
                self.console_handler.setLevel(logging.DEBUG)
            elif console_log_lever == 'info':
                self.console_handler.setLevel(logging.INFO)
            elif console_log_lever == 'warning':
                self.console_handler.setLevel(logging.WARNING)
            elif console_log_lever == 'error':
                self.console_handler.setLevel(logging.ERROR)
            elif console_log_lever == 'critical':
                self.console_handler.setLevel(logging.CRITICAL)

            # 设置控制台日志的格式
            self.console_handler.setFormatter(logging.Formatter(read_config_yaml('log','log_format')))

            # 将控制器加入日志对象
            self.logger.addHandler(self.console_handler)
        return self.logger
# 函数输出日志
def write_log(log_message):
    LoggerUtil().create_log().info(log_message)

def error_log(log_message):
    LoggerUtil().create_log().info(log_message)
    raise Exception (log_message)
if __name__ == '__main__':
    write_log("zhdadfdfdfdfd")
